from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                              QLineEdit, QPushButton, QMessageBox)
from contract_renamer.config import load_config, save_config
from pathlib import Path

class APIConfigDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
        self.load_config()
        
    def init_ui(self):
        """初始化对话框界面"""
        self.setWindowTitle("百度OCR API配置")
        self.setMinimumWidth(400)
        
        layout = QVBoxLayout(self)
        
        # APP ID
        app_id_layout = QHBoxLayout()
        app_id_label = QLabel("APP ID:")
        self.app_id_input = QLineEdit()
        app_id_layout.addWidget(app_id_label)
        app_id_layout.addWidget(self.app_id_input)
        layout.addLayout(app_id_layout)
        
        # API Key
        api_key_layout = QHBoxLayout()
        api_key_label = QLabel("API Key:")
        self.api_key_input = QLineEdit()
        api_key_layout.addWidget(api_key_label)
        api_key_layout.addWidget(self.api_key_input)
        layout.addLayout(api_key_layout)
        
        # Secret Key
        secret_key_layout = QHBoxLayout()
        secret_key_label = QLabel("Secret Key:")
        self.secret_key_input = QLineEdit()
        secret_key_layout.addWidget(secret_key_label)
        secret_key_layout.addWidget(self.secret_key_input)
        layout.addLayout(secret_key_layout)
        
        # 按钮
        button_layout = QHBoxLayout()
        save_button = QPushButton("保存")
        save_button.clicked.connect(self.save_config)
        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(save_button)
        button_layout.addWidget(cancel_button)
        layout.addLayout(button_layout)
        
    def load_config(self):
        """加载现有配置"""
        config = load_config()
        baidu_config = config.get('baidu_ocr', {})
        
        # 确保 app_id 是字符串
        app_id = baidu_config.get('app_id', '')
        self.app_id_input.setText(str(app_id) if app_id else '')
        self.api_key_input.setText(baidu_config.get('api_key', ''))
        self.secret_key_input.setText(baidu_config.get('secret_key', ''))
        
    def save_config(self):
        """保存配置"""
        try:
            # 获取输入值
            app_id = self.app_id_input.text().strip()
            api_key = self.api_key_input.text().strip()
            secret_key = self.secret_key_input.text().strip()
            
            # 验证输入
            if not all([app_id, api_key, secret_key]):
                QMessageBox.warning(self, "错误", "请填写所有必填项")
                return
            
            # 确保 app_id 是数字
            try:
                app_id = int(app_id)
            except ValueError:
                QMessageBox.warning(self, "错误", "APP ID 必须是数字")
                return
            
            # 加载现有配置
            config = load_config()
            
            # 更新百度OCR配置
            config['baidu_ocr'] = {
                'app_id': app_id,  # 保存为数字类型
                'api_key': api_key,
                'secret_key': secret_key
            }
            
            # 保存配置
            save_config(config)
            
            # 显示成功消息
            QMessageBox.information(self, "成功", "配置已保存")
            
            # 关闭对话框
            self.accept()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置失败：{str(e)}")